package com.test.udp.thread;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 使用多线程来实现同时发送
 * <p>
 * 发送端:使用面向对象封装
 *
 * @create: 2019-05-28 22:44
 **/
public class TalkSend implements Runnable {

    private DatagramSocket client;
    private BufferedReader reader;
    private String toIP;
    private int toPort;

    //创建构造方法,实例化socket对象
    public TalkSend(int port, String toIP, int toPort) {
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            client = new DatagramSocket(port);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            //使用循环来连续发送
            while (true) {
                //注意控制台输入时前后会有空格
                String data = reader.readLine().trim();
                byte[] datas = data.getBytes();
                //3.封装成DatagramPacket包裹,需要指定目的地(目标IP及端口号),注意地址要使用一个地址对象InetSocketAddress
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length,
                        new InetSocketAddress(toIP, toPort));

                //4.发送包裹send(DatagramPacket p)
                client.send(packet);

                //跳出循环
                if (data.equals("bye")) {
                    break;
                }
            }

            //5.释放资源
            reader.close();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
